<script setup lang="ts">
import { ref, reactive } from "vue"
import { ElMessage } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { createCertificateTempApi, updateCertificateTempApi, getCertificationNoTemplateApi } from "#/api/certificate/template"
import { obsUpload, obsDownload, obsDelete } from "#/utils/obs"
import { certificateType } from '../const'
import { trimStringParams } from '#/utils/trimStringParams'
import { Plus } from '@vben/icons';
import { cloneDeep } from '@vben/utils';
import {$t} from '#/locales'
import { getCertificationInfoByConditionApi } from "#/api/certificate/certificatesMgr"

defineOptions({ name: 'Dialog' })

const emit = defineEmits(['queryTable'])
const listLoading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogImageUrl = ref()
const imgVisible = ref(false)
const imgLoading = ref(false)
const title = ref()
const editData = ref()
const certifiListData = ref()
const defaultFrom = {
  name: '',
  type: '',
  templateFile: '',
  description: '',
  certificationId: ''
}
const formRef = ref()
const formInline = reactive({ ...defaultFrom })
const rules = {
  name: [{ required: true, message: $t('common.inputPhTxt', [$t('certificateTemplate.certificateNameTxt')]), trigger: 'blur' }],
  status: [{ required: true, message: $t('common.selectPhTxt', [$t('certificateTemplate.certificateStatusTxt')]), trigger: 'change' }],
  releaseTime: [{ required: true, message: $t('common.selectPhTxt', [$t('certificateTemplate.certificateReleaseTimeTxt')]), trigger: 'change' }],
  type: [{ required: true, message: $t('certificateTemplate.relatedCertificationTxt2'), trigger: 'change' }],
  certificationId: [{ required: true, message: $t('certificateTemplate.relatedCertificationTxt'), trigger: 'change' }],
  templateFile: [{ required: true, message: $t('certificateTemplate.uploadCertTemplateTxt'), trigger: 'change' }]
}
const fileList = ref<UploadUserFile[]>([])

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
  handleDeleteTemplate()
}

// 上传前检查
const beforeUpload = (file: File) => {
  const allowedTypes = ['image/bmp', 'image/png', 'image/jpeg', 'image/jpg']
  const isValidType = allowedTypes.includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isValidType) {
    ElMessage.error($t('certificateTemplate.onlySupportTxt'))
    return false
  }
  if (!isLt5M) {
    ElMessage.error($t('certificateTemplate.imageSizeTooLargeTxt'))
    return false
  }
  return true
}


const handleUpload = ({ file }: any) => {
  // 获取路由第一层路径（去掉开头的/）
  // 暂时使用本地URL预览
  // imgUrl.value = URL.createObjectURL(file)
  // 上传到 OBS，使用路由路径作为前缀
  obsUpload({
    Key: file.name,
    SourceFile: file
  }, (err: any, result: any, key: string) => {
    if (err) {
      ElMessage.error($t('common.uploadFailTxt'))
      return
    }
    // 上传成功后更新表单数据
    formInline.templateFile = key
    formRef.value?.clearValidate('templateFile')
    ElMessage.success($t('common.uploadSuccessTxt'))
  })

  return Promise.resolve()
}

const resObsUpload = (file: any, fileName: any) => {
  return new Promise((resolve, reject) => {
    obsUpload({
      Key: fileName,
      SourceFile: file,
    }, (err: any, result: any, key: string) => {
      if (err) {
        reject(err)
      }
      resolve(key)
    })
  })
}

const fileChange = (file: any, fileList: any) => {
  console.log(file)
  fileList.value = fileList
}

const download = async (templateFile: any) => {
  imgLoading.value = true
  const url = await resDownload(templateFile)
  imgLoading.value = false
  fileList.value = [
    { url, status: 'success', name: url }
  ] as any
}

const resDownload: any = (templateFile: any) => {
  return new Promise((resolve, reject) => {
    obsDownload({
      Key: templateFile,
      SaveByType: 'file'
    }, (err: any, result: any) => {
      if (err) {
        reject(err)
        return;
      }
      resolve(result?.InterfaceResult.Content.SignedUrl)
    })
  })
}

const handlePicturePreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  imgVisible.value = true
}

const handleClose = () => {
  Object.assign(formInline, defaultFrom)
  fileList.value = []
  dialogVisible.value = false
  formRef.value?.resetFields()
}

const getCertifiListData = () => {
  listLoading.value = true
  const API = title.value === $t('common.newTxt') ? getCertificationNoTemplateApi({}) : getCertificationInfoByConditionApi({
    pageNum: 1,
  })
  API.then(res => {
    let { data } = res;
    certifiListData.value = data ?? []
  }).finally(() => {
    listLoading.value = false
  })
}

const handleCertificationChange = (value: any) => {
  const certification = certifiListData.value.find((item: any) => item.id === value)
  formInline.type = certificateType.find((item: any) => item.type === certification?.type)?.name || ''
}

// 删除图标
const handleDeleteTemplate = () => {
  if (formInline.templateFile) {
    obsDelete({
      Key: formInline.templateFile
    }, (err: any, result: any) => {
      console.log(err, result)
      // if (err) {
      //   console.log(result)
      //   ElMessage.error($t('common.deleteFailTxt'))
      //   return
      // }
      // formInline.templateFile = ''
      // fileList.value = []
      // formRef.value?.validateField('templateFile')
      // ElMessage.success($t('common.deleteSuccessTxt'))
    })
  }

}

const inint = (data: any = null) => {
  title.value = data ? $t('common.editTxt') : $t('common.newTxt')
  if (data) {
    const { name, type, templateFile, description, certificationId } = data
    editData.value = data
    Object.assign(formInline, { name, type: certificateType.find((item: any) => item.type === type)?.name || '', templateFile, description, certificationId })
    if (templateFile) download(templateFile)
  }
  dialogVisible.value = true
  getCertifiListData()
}
const submit = () => {
  if (!formRef) return
  formRef.value?.validate((valid: any) => {
    if (valid) {
      const params = cloneDeep(formInline) as any
      params.type = certificateType.find((item: any) => item.name === params.type)?.type || ''
      if (title.value === $t('common.editTxt')) {
        params['id'] = editData.value.id
      }
      submitLoading.value = true
      const API = title.value === $t('common.newTxt') ? createCertificateTempApi(trimStringParams(params)) : updateCertificateTempApi(trimStringParams(params))
      API.then(() => {
        handleClose()
        const successTxt = title.value === $t('common.newTxt') ? $t('common.newTxt', [$t('common.successTxt')]) : $t('common.editTxt', [$t('common.successTxt')])
        ElMessage.success(successTxt)
        dialogVisible.value = false
        emit('queryTable')
      }).finally(() => {
        submitLoading.value = false
      })
    }
  })
}

defineExpose({ inint })

</script>
<template>
  <el-dialog v-model="dialogVisible" align-center :destroy-on-close="true" :title="`${title}`" width="800"
    :append-to-body="true" :close-on-click-modal="false" :before-close="handleClose">
    <div v-loading="listLoading" class="pl-[15px] pr-[15px] pt-[10px] pb-[10px] ">
      <el-form ref="formRef" :inline="true" label-width="110px" :rules="rules" :model="formInline"
        label-position="right">
        <el-form-item :label="$t('certificateTemplate.relatedCertificationTxt')" prop="certificationId" style="width:50%">
          <el-select :fit-input-width="true" @change="handleCertificationChange" :disabled="title === $t('common.editTxt')" filterable clearable v-model="formInline.certificationId"
            :placeholder="$t('common.selectPhTxt', [$t('certificateTemplate.relatedCertificationTxt')])">
            <el-option v-for="item in certifiListData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('certificateTemplate.certificateTypeTxt')" prop="type" style="width:50%">
          <el-input :disabled="title === $t('common.editTxt')" :placeholder="$t('certificateTemplate.certificateTypeTxt')" v-model="formInline.type" :readonly="true" />
          <!-- <el-select :disabled="title === $t('common.editTxt')" clearable v-model="formInline.type" :placeholder="$t('common.selectPhTxt', [$t('certificateTemplate.certificateTypeTxt')])">
            <el-option v-for="item in certificateType" :key="item.type" :label="item.name" :value="item.type" />
          </el-select> -->
        </el-form-item>
        <el-form-item :label="$t('certificateTemplate.certificateNameTxt')" prop="name" style="width:50%">
          <el-input type="text" :disabled="title === $t('common.editTxt')" :maxlength="50" style="width: 100%"
            v-model="formInline.name" :placeholder="$t('common.inputPhTxt', [$t('certificateTemplate.certificateNameTxt')])" />
        </el-form-item>
        <el-form-item :label="$t('certificateTemplate.certificateDescriptionTxt')" style="width:100%">
          <el-input type="textarea" :maxlength="500" show-word-limit v-model="formInline.description"
            :placeholder="$t('common.inputPhTxt', [$t('certificateTemplate.certificateDescriptionTxt')])" />
        </el-form-item>
        <el-form-item prop="templateFile" :label="$t('certificateTemplate.uploadCertTemplateTxt')" style="width:100%">
          <div>
            <div class="text-[#AEAEAE]">{{ $t('certificateTemplate.onlySupportTxt') }}</div>
            <el-upload v-model:file-list="fileList" accept="image/*"
              :on-preview="handlePicturePreview" @change="fileChange" class="update-war"
              :class="{ 'hide-upload-btn': fileList?.length > 0 }" :limit="1" action="#" :http-request="handleUpload"
              :auto-upload="true" list-type="picture-card" :on-remove="handleRemove" :before-upload="beforeUpload">
              <div>
                <Plus class="m-auto"/>
                <div class="text-[#AEAEAE]">{{ $t('certificateTemplate.uploadImgTxt') }}</div>
              </div>
            </el-upload>
          </div>  
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">
          {{ $t('common.cancelTxt') }}
        </el-button>
        <el-button type="primary" :disable="imgLoading" @click="submit" :loading="submitLoading">
          {{ $t('common.submitTxt') }}
        </el-button>
      </div>
    </template>
    <el-dialog align-center v-model="imgVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </el-dialog>
</template>
<style lang="less" scoped>
:deep(.el-form--inline .el-form-item) {
  margin-right: 0px;
}

.hide-upload-btn :deep(.el-upload--picture-card) {
  display: none !important;
}
</style>
